const jwt = require('jsonwebtoken');

// 确保所有地方使用相同的JWT密钥
const JWT_SECRET = 'pet-foster-secret-key-2024';

const auth = (req, res, next) => {
  try {
    const authHeader = req.header('Authorization');
    console.log('=== AUTH MIDDLEWARE DEBUG ===');
    console.log('Request URL:', req.url);
    console.log('Request Method:', req.method);
    console.log('Auth Header:', authHeader);
    console.log('All Headers:', req.headers);
    
    if (!authHeader) {
      console.log('❌ No Authorization header');
      return res.status(401).json({ error: '未提供访问令牌' });
    }

    const token = authHeader.replace('Bearer ', '');
    
    if (!token) {
      console.log('❌ No token after Bearer');
      return res.status(401).json({ error: '令牌格式错误' });
    }

    console.log('Token received:', token);
    console.log('JWT_SECRET:', JWT_SECRET);
    
    const decoded = jwt.verify(token, JWT_SECRET);
    console.log('✅ Token decoded successfully:', decoded);
    
    req.userId = decoded.userId;
    console.log('User ID set to:', req.userId);
    next();
  } catch (error) {
    console.error('❌ Token verification error:', error);
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({ error: '令牌已过期' });
    } else if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({ error: '令牌无效' });
    } else {
      return res.status(401).json({ error: '令牌验证失败' });
    }
  }
};

// 正确导出方式
module.exports = auth;
// 同时导出JWT_SECRET供其他模块使用
module.exports.JWT_SECRET = JWT_SECRET;